package com.qianying.service.impl;

import com.qianying.comment.CommonResult;
import com.qianying.dto.WorkOrderDTO;
import com.qianying.entity.WorkOrder;
import com.qianying.mapper.WorkOrderMapper;
import com.qianying.service.IWorkOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author check
 * @since 2025-07-17
 */
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements IWorkOrderService {
    @Override
    public CommonResult<?> addOrder(WorkOrderDTO workOrderDTO) {

        if (workOrderDTO == null) {
            return CommonResult.failed("订单对象为空，不能创建对象");
        }
        WorkOrder workOrder = workOrderDTO.toEntity();
        if (this.save(workOrder)) {
            return CommonResult.success("创建订单成功！");
        } else {
            return CommonResult.failed("创建订单失败！");
        }
    }

    public static String genOrderNo(long userId) {
        AtomicInteger seqCounter = new AtomicInteger(0);
        int seqMask = 999;
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String timePart = LocalDateTime.now().format(fmt);

        // seqCounter 每次调用都会重新初始化为0，可能导致序号重复，
        // 这里演示改为函数局部变量，但要保证并发唯一需要其他方案，比如外部传入或静态变量
        int seq = seqCounter.getAndIncrement() & seqMask;

        return  "Order_"+timePart+userId + String.format("%03d", seq);
    }


}

